<template>
  <div>
    <a-form
      :model="postData"
      name="basic"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 12 }"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item
        label="帖子标题"
        name="postTitle"
        :rules="[{ required: true, message: '请输入帖子标题！' }]"
      >
        <a-input
          :disabled="isShow"
          v-model:value="postData.postTitle"
          placeholder="请输入帖子标题"
        />
      </a-form-item>
      <a-form-item
        label="帖子内容"
        name="postContent"
        :rules="[{ required: true, message: '请输入帖子内容！' }]"
      >
        <a-textarea
          :disabled="isShow"
          v-model:value="postData.postContent"
          placeholder="请输入帖子内容"
          :rows="4"
        />
      </a-form-item>

      <!-- 上传照片 -->
      <a-form-item v-if="!isShow" label="帖子图片" name="postContent">
        <a-upload
          v-model:file-list="fileList"
          action="http://localhost:8099/common/uploadOss"
          list-type="picture-card"
          @preview="handlePreview"
          @remove="deleteFile"
        >
          <div v-if="fileList.length < 9">
            <plus-outlined />
            <div style="margin-top: 8px">上传图片</div>
          </div>
        </a-upload>
        <a-modal
          :open="previewVisible"
          :title="previewTitle"
          :footer="null"
          @cancel="handleCancel"
        >
          <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
      </a-form-item>

      <template v-else>
        <a-form-item label="帖子图片" v-if="postData.images">
          <div class="image-box">
            <a-image
              v-for="(item, index) in postData.images"
              :key="index"
              style="border-radius: 8px"
              width="24%"
              :src="item"
            />
            <!-- <a-image
              v-for="(item, index) in postData.images"
              :key="index"
              style="border-radius: 8px"
              :width="100"
              :src="item"
            /> -->
          </div>
        </a-form-item>

        <a-form-item label="帖子状态">
          <a-select
            placeholder="请选择帖子状态"
            ref="select"
            v-model:value="postData.postStatus"
          >
            <a-select-option :value="1">待审核</a-select-option>
            <a-select-option :value="2">审核通过</a-select-option>
            <a-select-option :value="3">审核不通过</a-select-option>
            <a-select-option :value="4">已回收</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="发帖人姓名">
          <a-input disabled v-model:value="showInfo.employee.name" />
        </a-form-item>
        <a-form-item label="发帖人所属社区">
          <a-input disabled v-model:value="showInfo.community.communityName" />
        </a-form-item>
      </template>

      <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
        <a-button
          style="margin-right: 20px; background-color: #b83b5e"
          type="primary"
          html-type="submit"
          >提交</a-button
        >
        <a-button v-if="!isShow" @click="reset">重置</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { apiAdd, apiGetForumDetails, apiSetPostStatus } from '@/api/Forum/api'
import { PlusOutlined } from '@ant-design/icons-vue'
import { FourmDataModel } from '@/api/Forum/Model'
import { message, type UploadProps } from 'ant-design-vue'
import { userUserStore } from '@/stores/UserStore'
import { deleteOssImage } from '@/api/config/api'
const store = userUserStore()
const emit = defineEmits(['receiveData'])
const props = defineProps(['postId'])
const postData = ref<FourmDataModel>({
  postId: null,
  postTitle: '',
  postContent: '',
  images: '',
  coverImg: '',
  empId: null,
  communityId: null,
  postStatus: null,
})

//是否是展示状态
const isShow = ref<boolean>(false)
const showInfo = ref()

const fileList = ref<any>([])

//重置表单数据
const reset = async () => {
  if (fileList.value.length != 0) {
    fileList.value.forEach(async (ele: string) => {
      await deleteFile(ele)
    })
    fileList.value = []
  }

  Object.keys(postData.value).forEach((key) => delete postData.value[key])
}
const onFinish = async () => {
  //判断是不是修改状态
  if (isShow.value) {
    try {
      await apiSetPostStatus({
        postId: postData.value.postId,
        postStatus: postData.value.postStatus,
      })
      return emit('receiveData', 1)
    } catch (error) {
      return emit('receiveData', 2)
    }
  }
  // 判断有没有上传图片
  if (fileList.value.length != 0) {
    // 将帖子中的图片转字符串
    postData.value.coverImg = fileList.value[0].response.data
    let imgArr: Array<String> = []
    fileList.value.forEach((ele: any) => {
      imgArr.push(ele.response.data)
    })
    postData.value.images = JSON.stringify(imgArr)
  }
  //获取用户信息
  postData.value.empId = userInfo.value.empId
  postData.value.communityId = userInfo.value.communityId

  try {
    await apiAdd(postData.value)
    emit('receiveData', 3)
  } catch (error) {
    emit('receiveData', 4)
  }
}

const onFinishFailed = () => {
  message.error('请填写表单数据')
}

// 删除图片
const deleteFile = async (e: any) => {
  await deleteOssImage({
    file: e.response.data,
  })
}

function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader: any = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error: any) => reject(error)
  })
}

const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')

const handleCancel = () => {
  previewVisible.value = false
  previewTitle.value = ''
}
const handlePreview = async (file: UploadProps['fileList'][number]) => {
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string
  }
  previewImage.value = file.url || file.preview
  previewVisible.value = true
  previewTitle.value =
    file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}

const userInfo = ref<any>({})

onMounted(async () => {
  userInfo.value = store.employeeInfo
  if (props.postId != 0) {
    //去获取帖子详情 将数据进行展示
    let res = await apiGetForumDetails(props.postId)
    isShow.value = true
    postData.value = res.data.forum
    showInfo.value = res.data
    if (postData.value.images != '') {
      postData.value.images = JSON.parse(postData.value.images)
    }
  }
})
</script>

<style lang="less" scoped>
.image-box {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  ::v-deep(.ant-image) {
    margin: 10px 12px 0 0;
    overflow: hidden;
  }
}
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
